package the.formula.calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;

public class QuadraticFormula extends Activity{

	private TableLayout tl;
	private EditText Acoefficient;
	private EditText Bcoefficient;
	private EditText Ccoefficient;
	private String[] sCoefficients = new String[3];
	private double[] numCoefficients = new double[3];
	private double answer1;
	private double answer2;
	private TextView tv;
	private TextView tv2;
	private boolean answerAdded = true;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quadratic_formula);
        tl = (TableLayout)findViewById(R.id.quadraticLayout);
        tv = new TextView(this);
        tv2 = new TextView(this);
    }
        
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.quadraticSolve:
            	solveQuadratic();
                break;
        }
    }
        
    private void solveQuadratic() {
		Acoefficient = (EditText)findViewById(R.id.Acoefficient);
		Bcoefficient = (EditText)findViewById(R.id.Bcoefficient);
		Ccoefficient = (EditText)findViewById(R.id.Ccoefficient);
		
		sCoefficients[0] = Acoefficient.getText().toString();
		sCoefficients[1] = Bcoefficient.getText().toString();
		sCoefficients[2] = Ccoefficient.getText().toString();
		
		for(int i = 0; i < sCoefficients.length; i++) {
			numCoefficients[i] = Double.parseDouble(sCoefficients[i]);
		}
		
		if(answerAdded) {
			tl.removeView(tv);
			tl.removeView(tv2);
		}
		
		if(numCoefficients[1] * numCoefficients[1] >= 4 * numCoefficients[0] * numCoefficients[2]) {
			answer1 = quadraticFormulaPositive(numCoefficients[0], numCoefficients[1], numCoefficients[2]);
			answer2 = quadraticFormulaNegative(numCoefficients[0], numCoefficients[1], numCoefficients[2]);
			tv.setText("x= " + answer1);
			tv2.setText("x= " + answer2);
		} else {
			tv.setText("Answer does not exist");
			tv2.setText("");
		}
		tl.addView(tv);
		tl.addView(tv2);
		answerAdded = true;
	}

	private double quadraticFormulaPositive(double a, double b, double c) {
        double result = (-b + Math.sqrt(b * b - 4 * a * c) / (2 * a));
        return result;
    }
        
    private double quadraticFormulaNegative(double a, double b, double c) {
        double result = (-b - Math.sqrt(b * b - 4 * a * c) / (2 * a));
        return result;
    }
}